package org.simple.learning.springbootlogback;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目名称：spring-boot-learning
 * 类名称：ThresholdFilterPlus
 * 类描述：ThresholdFilterPlus
 * 创建时间：2019/2/22
 *
 * @author guihuo   (E-mail:1620657419@qq.com)
 * @version v1.0
 */
public class ThresholdFilterPlus extends Filter<ILoggingEvent> {

    private List<String> logNameStartsWith = new ArrayList<>();

    private Level level = Level.INFO;

    public void setLogNameStartWith(String logNameStartsWith) {
        this.logNameStartsWith.add(logNameStartsWith);
    }

    public void setLevel(String level) {
        this.level = Level.toLevel(level);
    }

    @Override
    public void start() {
        if (this.level != null && this.logNameStartsWith != null) {
            super.start();
        }
    }

    @Override
    public FilterReply decide(ILoggingEvent event) {
        String loggerName = event.getLoggerName();
        if (logNameStartsWith != null) {
            for (String item : logNameStartsWith) {
                if (loggerName.startsWith(item)) {
                    if (event.getLevel().isGreaterOrEqual(level)) {
                        return FilterReply.NEUTRAL;
                    }
                }
            }
        }
        return FilterReply.DENY;
    }

}
